package com.ssm.web.action;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ssm.bean.News;
import com.ssm.bean.SimpleUser;
import com.ssm.util.Constant;
import com.ssm.util.MD5;
import com.ssm.util.SessionBean;
import com.ssm.util.StringUtil;
import com.ssm.util.common.BaseAction;
import com.ssm.web.service.NewsService;
import com.ssm.web.service.SimpleUserService;
import com.ssm.web.service.SysUserService;

@Controller
@RequestMapping("/com")
public class LoginAction extends BaseAction {
	@Autowired
	private SysUserService		sysUserService;
	@Autowired
	private SimpleUserService	simpleUserService;
	@Autowired
	private NewsService				newsService;

	@RequestMapping(value = "/login.do")
	public String login(String username, String password, String loginType, String checkcode) throws Exception {
		log.info(username + " " + password + " " + loginType);
		String errorMessage = "登录失败,请稍候重试";
		try {
			String code = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			if (code == null) {
				request.getSession(false).invalidate();
				return "redirect:/index.jsp";
			} else {
			}
			checkcode = StringUtil.stringVerification(checkcode);
			do {
				if (!code.toLowerCase().equals(checkcode.toLowerCase())) {
					errorMessage = "验证码错误";
					break;
				}
				username = StringUtil.stringVerification(username).toLowerCase();
				MD5 md = new MD5();
				password = md.getMD5ofStr(password);
				Object bean = sysUserService.login(username, password, loginType);
				if (bean == null) {
					errorMessage = "账号或者密码错误";
					break;
				}

				SessionBean sb = new SessionBean();
				sb.setUser(bean);
				session.setAttribute(Constant.SESSION_BEAN, sb);

				putSessionValue("sysnewslist", newsService.selectAll(News.class, "id desc"));
				if (loginType.equals(SimpleUser.class.getSimpleName())) {
					//					return "redirect:/exit.jsp";
				}
				return "main";

			} while (false);

		} catch (Exception e) {
			e.printStackTrace();
		}
		session.setAttribute("signErrorMessage", errorMessage);
		return "redirect:/index.jsp";
	}

	@RequestMapping(value = "/reg.do")
	public String add(SimpleUser bean) {
		try {
			SimpleUser temp = simpleUserService.findByUname(bean.getUname());
			if (temp != null) {
				putSessionValue("signErrorMessage", "很遗憾,账号已经被使用.");
			} else {
				bean.setUserGender("男");
				simpleUserService.addSimpleUser(bean);
				putSessionValue("signErrorMessage", "恭喜您! 注册成功.");
			}
		} catch (Exception e) {
			e.printStackTrace();
			putSessionValue("signErrorMessage", "很遗憾,注册失败.");
		}

		return "redirect:/reg.jsp";

	}

	@RequestMapping(value = "/pwd.do")
	public String pwd(SimpleUser bean) {
		try {
			SimpleUser temp = simpleUserService.findByUname(bean.getUname());
			if (temp == null) {
				putSessionValue("signErrorMessage", "账号信息不存在");
			} else {
				if (bean.getQuestion().equals(temp.getQuestion()) && bean.getAnswer().equals(temp.getAnswer())) {
					temp.setUserPassword(bean.getUserPassword());
					simpleUserService.updateSimpleUser(temp);
					putSessionValue("signErrorMessage", "重置密码成功");
				}else{
					putSessionValue("signErrorMessage", "密保信息错误");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			putSessionValue("signErrorMessage", "重置密码失败");
		}

		return "redirect:/pwd.jsp";

	}

	@RequestMapping(value = "/toSelf.do")
	public String toSelf() {
		return "msg/modifySelf";
	}

	@RequestMapping(value = "/logout.do")
	public String logout() {
		session.invalidate();
		return "redirect:/exit.jsp";
	}

	@RequestMapping(value = "/fileUpload.do", method = RequestMethod.POST)
	@ResponseBody
	public Object image(HttpServletRequest request, HttpSession session, @RequestParam("upload") MultipartFile file) throws Exception {

		final String prefix = "/resource";

		final String realPath = session.getServletContext().getRealPath(prefix);
		File dir = new File(realPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		// 取得原文件名	
		String originName = file.getOriginalFilename();
		// 取得文件后缀
		String fileExt = originName.substring(originName.lastIndexOf(".") + 1);
		// 按时间戳生成图片文件名
		String picture = new Date().getTime() + "." + fileExt;
		FileOutputStream fout = new FileOutputStream(new File(dir, picture));
		try {
			IOUtils.copy(file.getInputStream(), fout);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fout.close();
			} catch (Exception e) {
			}
		}
		// {'err':'',msg:{'url':'XXX/upload/images/2012/11_11/20121111015039.jpg','localname':'我的头像.jpg','id':'63'}}
		//String json = String.format("{'statusCode':200,'message':'上传成功!','filename':'%s'}", picture);
		JSONObject obj = new JSONObject();
		obj.put("statusCode", 200);
		obj.put("message", "");
		obj.put("filename", picture);
		return obj;
	}
	/**
				<tr>
					<td>
						<label class="control-label x150">testFile：</label>
						<div style="display: inline-block; vertical-align: middle;">
							<div id="j_custom_pic_up" 
								data-toggle="upload" data-uploader="${ctx}/com/fileUpload.do"
								data-file-size-limit="2024000000" 
								data-file-type-exts="*.jpg;*.png;*.gif;*.mpg" 
								data-multi="true"
								data-on-upload-success="pic_upload_success"
								data-file-obj-name="upload" 
								data-icon="cloud-upload">
							</div>
							<input type="hidden" name="testFile" data-rule="required" value="${modifybean.testFile}" id="j_custom_pic">
							<span id="j_custom_span_pic"> </span>
						</div>
					</td>
				</tr>
	*/

	/**
				<tr>
					<td>
						<label for="Plan_content" class="control-label x150">内容：</label>
						<div style="display: inline-block; vertical-align: middle;">
							<textarea name="content" id="j_form_content" class="j-content" style="width: 700px;" data-toggle="kindeditor"
								data-items="fontname, fontsize, |, forecolor, hilitecolor, bold, italic, underline, removeformat, |, justifyleft, justifycenter, justifyright, insertorderedlist, insertunorderedlist, |, emoticons, image, link"
								data-minheight="200px">${modifybean.content }</textarea>
						</div>
					</td>
				</tr>
	*/
}
